<?php


namespace app\h5\controller;


use app\common\controller\H5Controller;
use app\common\lib\RespCode;
use custom\Log;
use custom\Redis;
use think\Exception;

class Share extends H5Controller {

    public function index() {
        try {
            $params = $this->checkParams ('url');
            Log::write ('url->'.$params["url"], 'h5_share.log');
            $grant_type = 'client_credential';
            //$appid = 'wx41349835fc7058b7';
            //$secret = 'cc79247884a14c4dbba74aa5f0bf6013';
            $appid = 'wx9051f8def3717ac3';
            $secret = 'd6429eae4643188d8048b80658d21a3e';
            if ($params === false) return $this->resErr ();
            $redis = Redis::getInstance ();
            //取$ticket
            $ticket = $redis->get ('h5_share_ticket');
            Log::write ('ticket->'.$ticket, 'h5_share.log');
            //没有$ticket，重新获取
            if($ticket===false){
                //取$ACCESS_TOKEN
                $ACCESS_TOKEN = $redis->get ('h5_share_access_token');
                //没有$ACCESS_TOKEN，重新获取
                if($ACCESS_TOKEN === false){
                    $json1 = file_get_contents ("https://api.weixin.qq.com/cgi-bin/token?grant_type={$grant_type}&appid={$appid}&secret={$secret}");
                    Log::write ('json1->' . $json1, 'h5_share.log');
                    $json1 = json_decode ($json1, true);
                    if (!isset($json1['access_token'])) return $this->resErr('获取access_token失败', RespCode::DATA_ERR);
                    $ACCESS_TOKEN=$json1["access_token"];
                    $redis->setex ('h5_share_access_token', 7200, $ACCESS_TOKEN);
                }
                $json2 = file_get_contents ("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$ACCESS_TOKEN}&type=jsapi");
                Log::write ('json2->' . $json2, 'h5_share.log');
                $json2 = json_decode ($json2, true);
                if (!isset($json2['ticket'])) return $this->resErr('获取ticket失败', RespCode::DATA_ERR);
                $ticket=$json2['ticket'];
                $redis->setex ('h5_share_ticket', 7200, $ticket);
            }
            $timestamp=time();
            $nonceStr=md5 ($timestamp);
            $string1="jsapi_ticket={$ticket}&noncestr={$nonceStr}&timestamp={$timestamp}&url={$params['url']}";
            $signature = sha1 ( ($string1));
            return $this->resData('success', compact('signature', 'appid', 'nonceStr', 'timestamp'));
        } catch (Exception $e) {
            return $this->resErr ($e->getMessage (), $e->getCode ());
        }
    }

}
